package com.situ.yB2C.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import com.situ.yB2C.util.ContextUtil;

/**
 * #买家登录状态拦截器
 * #继承 HandlerInterceptorAdapter  extends HandlerInterceptorAdapter 过期了
 * #实现 HandlerInterceptor 接口
 * 
 * @author YH
 * 
 */

public class BuyerLoginInterceptor implements HandlerInterceptor {

	private static final Logger LOG = LoggerFactory.getLogger(BuyerLoginInterceptor.class);
	private static final String XHR_OBJECT_NAME = "XMLHttpRequest"; //jQuery的Ajax请求的头文件的值；
	private static final String HEADER_REQUEST_WITH = "x-requested-with";//jQuery 在发起Ajax请求时，携带的头文件信息
	private static final Integer AJAX_REQUEST_STATUS_CODE_NOLOGIN =700; //Ajax请求的未登录返回状态码
	/**
	 * # 对 进controller层之前的请求进行过滤
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI().toString();
		
		LOG.debug(url + "请求过拦截器");
		//判断当前用户是否处在登录状态
		HttpSession session = request.getSession();
		Object object = session.getAttribute(ContextUtil.SESSION_LOGIN_BUYER);
		if(object ==null) {//判断当前用户处在非登录状态
			//判断 是否为异步请求
			boolean isAjax =isAjaxRequest(request);
			//如果是异步请求
			if(isAjax) {
				//根据项目的设计 返回定义的状态码，这个状态码有增强的jQuery的ajax进行响应
				response.setStatus(AJAX_REQUEST_STATUS_CODE_NOLOGIN);
			}else {
				//如果是同步的请求，则直接发起重定向到达登录页面
				response.sendRedirect("gologin");
			}
			
			
			//将当前的请求拦在这个拦截器
			return false;
		}else {//判断用户处在登录状态
			//放当前的请求过拦截器
			return true;
		}
		
		
		//return super.preHandle(request, response, handler);
	}
	private boolean isAjaxRequest(HttpServletRequest request) {
		String jQueryXHRObjectName = request.getHeader(HEADER_REQUEST_WITH);
		if(jQueryXHRObjectName !=null && XHR_OBJECT_NAME.equals(jQueryXHRObjectName)) {
			return true;
		}else {
			return false;
		}
	}
}











